<?php
require_once 'config.php';
$timerData = getTimerData();
$currentTime = $timerData['elapsed_time'];
if ($timerData['is_running'] && $timerData['start_time']) {
    $currentTime += (time() - $timerData['start_time']);
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>管理员远程控制</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
        }
        .container {
            max-width: 600px;
            margin: 20px auto;
            background: rgba(255, 255, 255, 0.95);
            padding: 25px;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
        }
        h1 {
            text-align: center;
            color: #2d3748;
            margin-bottom: 25px;
            font-size: 28px;
        }
        .status-panel {
            background: linear-gradient(135deg, #edf2f7, #e2e8f0);
            padding: 20px;
            border-radius: 12px;
            margin: 20px 0;
            text-align: center;
            border: 2px solid #e2e8f0;
        }
        .timer-display {
            font-size: 32px;
            font-family: 'Courier New', monospace;
            color: #2d3748;
            margin: 15px 0;
            font-weight: bold;
        }
        .status-text {
            font-size: 18px;
            font-weight: bold;
            padding: 8px 16px;
            border-radius: 20px;
            display: inline-block;
        }
        .status-running {
            background: #c6f6d5;
            color: #22543d;
        }
        .status-stopped {
            background: #fed7d7;
            color: #742a2a;
        }
        .scores {
            display: flex;
            justify-content: space-around;
            margin: 25px 0;
            gap: 15px;
        }
        .blue-score, .red-score {
            padding: 15px 25px;
            border-radius: 12px;
            font-weight: bold;
            font-size: 20px;
            flex: 1;
            text-align: center;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
        }
        .blue-score {
            background: linear-gradient(135deg, #dbeafe, #93c5fd);
            color: #1e40af;
            border: 2px solid #3b82f6;
        }
        .red-score {
            background: linear-gradient(135deg, #fee2e2, #fca5a5);
            color: #b91c1c;
            border: 2px solid #ef4444;
        }
        .control-buttons {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 15px;
            margin: 25px 0;
        }
        button {
            padding: 16px 20px;
            border: none;
            border-radius: 10px;
            cursor: pointer;
            font-weight: bold;
            font-size: 16px;
            transition: all 0.3s ease;
        }
        button:hover {
            transform: translateY(-2px);
        }
        .start-btn {
            background: linear-gradient(135deg, #10b981, #059669);
            color: white;
        }
        .stop-btn {
            background: linear-gradient(135deg, #ef4444, #dc2626);
            color: white;
        }
        .reset-btn {
            background: linear-gradient(135deg, #6b7280, #4b5563);
            color: white;
            grid-column: span 2;
        }
        .connection-status {
            text-align: center;
            margin: 15px 0;
            padding: 12px;
            border-radius: 8px;
            font-weight: bold;
        }
        .connected {
            background: #dcfce7;
            color: #166534;
        }
        .disconnected {
            background: #fee2e2;
            color: #b91c1c;
        }
        .loading {
            opacity: 0.7;
        }
        .reset-confirm {
            display: none;
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: white;
            padding: 25px;
            border-radius: 12px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
            z-index: 1000;
            text-align: center;
        }
        .reset-confirm-buttons {
            display: flex;
            gap: 15px;
            justify-content: center;
            margin-top: 20px;
        }
        .confirm-btn, .cancel-btn {
            padding: 10px 20px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
        }
        .confirm-btn {
            background: #ef4444;
            color: white;
        }
        .cancel-btn {
            background: #6b7280;
            color: white;
        }
        .overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            z-index: 999;
        }
        .notification {
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 15px 20px;
            border-radius: 8px;
            color: white;
            font-weight: bold;
            opacity: 0;
            transform: translateX(100%);
            transition: all 0.3s ease;
            z-index: 1000;
        }
        .notification.success {
            background: #10b981;
            opacity: 1;
            transform: translateX(0);
        }
        .notification.error {
            background: #ef4444;
            opacity: 1;
            transform: translateX(0);
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>管理员远程控制</h1>
        
        <div class="connection-status" id="connection-status">连接中...</div>
        
        <div class="status-panel">
            <div class="timer-display" id="timer"><?php echo gmdate("H:i:s", $currentTime); ?></div>
            <div class="status-text <?php echo $timerData['is_running'] ? 'status-running' : 'status-stopped'; ?>" id="status-text">
                <?php echo $timerData['is_running'] ? '运行中' : '已停止'; ?>
            </div>
        </div>
        
        <div class="scores">
            <div class="blue-score" id="blue-score">蓝方: <?php echo $timerData['blue_score']; ?></div>
            <div class="red-score" id="red-score">红方: <?php echo $timerData['red_score']; ?></div>
        </div>
        
        <div class="control-buttons">
            <button class="start-btn" id="start-btn" onclick="controlTimer('start')">开始计时</button>
            <button class="stop-btn" id="stop-btn" onclick="controlTimer('stop')">停止计时</button>
            <button class="reset-btn" id="reset-btn" onclick="showResetConfirm()">重置所有数据</button>
        </div>
    </div>

    <div class="overlay" id="overlay" onclick="hideResetConfirm()"></div>
    <div class="reset-confirm" id="reset-confirm">
        <h3>确认重置</h3>
        <p>确定要重置所有数据吗？</p>
        <p style="color: #ef4444; font-weight: bold;">计时器、蓝方分数、红方分数都将归零！</p>
        <div class="reset-confirm-buttons">
            <button class="confirm-btn" onclick="performReset()">确认重置</button>
            <button class="cancel-btn" onclick="hideResetConfirm()">取消</button>
        </div>
    </div>

    <div id="notification" class="notification"></div>

    <script>
        const API_URL = 'api.php';
        let currentState = {
            elapsed_time: <?php echo $currentTime; ?>,
            is_running: <?php echo $timerData['is_running'] ? 'true' : 'false'; ?>,
            blue_score: <?php echo $timerData['blue_score']; ?>,
            red_score: <?php echo $timerData['red_score']; ?>
        };

        window.addEventListener('load', function() {
            fetchData();
            setInterval(fetchData, 2000);
            updateButtonStates();
        });

        function showResetConfirm() {
            document.getElementById('reset-confirm').style.display = 'block';
            document.getElementById('overlay').style.display = 'block';
        }

        function hideResetConfirm() {
            document.getElementById('reset-confirm').style.display = 'none';
            document.getElementById('overlay').style.display = 'none';
        }

        function performReset() {
            hideResetConfirm();
            setButtonLoading('reset-btn', true);
            
            fetch(API_URL, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'action=reset_all'
            })
            .then(response => response.json())
            .then(data => {
                if (data && data.success) {
                    showNotification('重置成功', 'success');
                    updateDisplayAfterReset();
                    setTimeout(fetchData, 500);
                } else {
                    throw new Error(data?.message || '重置失败');
                }
            })
            .catch(error => {
                showNotification('重置失败: ' + error.message, 'error');
            })
            .finally(() => {
                setButtonLoading('reset-btn', false);
            });
        }

        function updateDisplayAfterReset() {
            document.getElementById('timer').textContent = '00:00:00';
            document.getElementById('blue-score').textContent = '蓝方: 0';
            document.getElementById('red-score').textContent = '红方: 0';
            
            const statusText = document.getElementById('status-text');
            statusText.textContent = '已停止';
            statusText.className = 'status-text status-stopped';
            
            updateButtonStates();
        }

        function fetchData() {
            fetch(API_URL + '?action=get_data&t=' + Date.now())
                .then(response => response.json())
                .then(data => {
                    if (data && data.success) {
                        updateDisplay(data.data);
                        setConnected(true);
                    }
                })
                .catch(error => {
                    setConnected(false);
                });
        }

        function updateDisplay(data) {
            currentState = data;
            updateTimerDisplay(data.elapsed_time);
            document.getElementById('blue-score').textContent = `蓝方: ${data.blue_score}`;
            document.getElementById('red-score').textContent = `红方: ${data.red_score}`;
            
            const statusText = document.getElementById('status-text');
            statusText.textContent = data.is_running ? '运行中' : '已停止';
            statusText.className = `status-text ${data.is_running ? 'status-running' : 'status-stopped'}`;
            
            updateButtonStates();
        }

        function updateTimerDisplay(seconds) {
            const hours = Math.floor(seconds / 3600);
            const minutes = Math.floor((seconds % 3600) / 60);
            const secs = seconds % 60;
            document.getElementById('timer').textContent = 
                `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
        }

        function controlTimer(action) {
            const buttonId = action === 'start' ? 'start-btn' : 'stop-btn';
            setButtonLoading(buttonId, true);
            
            const formData = new URLSearchParams();
            formData.append('action', action === 'start' ? 'start_timer' : 'stop_timer');
            
            fetch(API_URL, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data && data.success) {
                    showNotification(action === 'start' ? '计时器已启动' : '计时器已停止', 'success');
                    fetchData();
                }
            })
            .catch(error => {
                showNotification('操作失败', 'error');
            })
            .finally(() => {
                setButtonLoading(buttonId, false);
            });
        }

        function updateButtonStates() {
            const startBtn = document.getElementById('start-btn');
            const stopBtn = document.getElementById('stop-btn');
            
            if (currentState.is_running) {
                startBtn.disabled = true;
                stopBtn.disabled = false;
            } else {
                startBtn.disabled = false;
                stopBtn.disabled = true;
            }
        }

        function setButtonLoading(buttonId, loading) {
            const button = document.getElementById(buttonId);
            if (loading) {
                button.disabled = true;
                button.innerHTML = '处理中...';
            } else {
                button.disabled = false;
                button.innerHTML = buttonId === 'start-btn' ? '开始计时' : 
                                 buttonId === 'stop-btn' ? '停止计时' : '重置所有数据';
                updateButtonStates();
            }
        }

        function setConnected(connected) {
            const statusEl = document.getElementById('connection-status');
            if (connected) {
                statusEl.textContent = '已连接到服务器';
                statusEl.className = 'connection-status connected';
            } else {
                statusEl.textContent = '服务器连接断开';
                statusEl.className = 'connection-status disconnected';
            }
        }

        function showNotification(message, type) {
            const notification = document.getElementById('notification');
            notification.textContent = message;
            notification.className = `notification ${type}`;
            
            setTimeout(() => {
                notification.className = 'notification';
            }, 3000);
        }
    </script>
</body>
</html>